import { Text, View } from "@tarojs/components";
import styles from "./index.scss";
import { Button, Form } from "@nutui/nutui-react-taro";
import { setToken, setUserInfo } from "@/utils/token";
import Taro from "@tarojs/taro";
import {login } from "@/services/User";
import { useRequest } from "taro-hooks";
import Input from "@/components/Input";
import InputPassword from "@/components/Input/InputPassword";
import { useFamilyStore } from "@/model";

const Index = () => {
  const [form] = Form.useForm();
  const {setFamily} = useFamilyStore();
  const { run } = useRequest(login, {
    manual: true,
    onSuccess: (res: any) => {
      setToken(res?.token);
      setUserInfo(res);
      setFamily({})
      Taro.redirectTo({
        url: "/innerPages/family/index",
      });
    },
  });

  const InputValidator = (_ruleCfg, value: any) => {
    if (!value?.length) return false;
    return true;
  };

  return (
    <View className={styles.container}>
      <View className={styles.title}>家庭物资管理系统</View>
      <View className={styles.content}>
        <Form
          labelPosition="top"
          form={form}
          onFinish={(v) => {
            run(v);
          }}
          footer={
            <View className={styles.footer}>
              <View className={styles.register}>
                <Text>没有账号？</Text>
                <Text
                  className={styles.toRegister}
                  onClick={() => {
                    Taro.navigateTo({
                      url: "/loginAndRegister/register/index",
                    });
                  }}
                >
                  去注册
                </Text>
              </View>
              <View className="">
                <Button className={styles.btn} onClick={() => form.submit()}>
                  登录
                </Button>
              </View>
            </View>
          }
        >
          <Form.Item
            label="账号"
            name="account"
            rules={[
              {
                validator: InputValidator,
                message: "账号不能为空",
              },
              { max: 10, message: "账号不超过10位" },
            ]}
          >
            <Input className={styles.input} placeholder="请输入账号" />
          </Form.Item>
          <Form.Item
            label="密码"
            name="password"
            rules={[
              {
                validator: InputValidator,
                message: "密码不能为空",
              },
              { max: 10, message: "密码不超过10位" },
            ]}
          >
            <InputPassword className={styles.input} placeholder="请输入密码" />
          </Form.Item>
        </Form>
      </View>
    </View>
  );
};

export default Index;
